package com.youga.imageselector;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Window;
import android.widget.Toast;

import com.youga.imageselector.util.PermissionUtil;
import com.youga.imageselector.util.Utils;

import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by Youga on 2016/1/7.
 */
public class CameraFragment extends DialogFragment {

    public static final String TAG = "CamceaFragment";
    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 44;
    private static final int REQUEST_CAMERA = 55;
    private static final int CAMERA_REQUEST_CODE = 33;
    CameraCallBack mCallBack;

    public static CameraFragment newInstance(CameraCallBack choiceCallBack) {
        CameraFragment fragment = new CameraFragment();
        fragment.setCameraCallBack(choiceCallBack);
        return fragment;
    }


    public static CameraFragment openCamera(FragmentManager manager, CameraCallBack cameraCallBack) {
        FragmentTransaction ft = manager.beginTransaction();
        Fragment prev = manager.findFragmentByTag(TAG);
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        ft.commitAllowingStateLoss();

        CameraFragment fragment = CameraFragment.newInstance(cameraCallBack);
        fragment.show(manager, TAG);
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (!PermissionUtil.mayWriteExternalStorage(getActivity(),
                REQUEST_WRITE_EXTERNAL_STORAGE,
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void shouldShowAlertDialog(String title) {
                        mCallBack.shouldShowAlertDialog(title);
                    }
                })) {
            return;
        }

        if (!PermissionUtil.mayCamera(getActivity(),
                REQUEST_CAMERA,
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void shouldShowAlertDialog(String title) {
                        mCallBack.shouldShowAlertDialog(title);
                    }
                })) {
            return;
        }

        openCamera();
    }

    public void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Utils.createImageFile()));
            startActivityForResult(intent, CAMERA_REQUEST_CODE);
        } else {
            Toast.makeText(getActivity(), R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        switch (requestCode) {
            case REQUEST_WRITE_EXTERNAL_STORAGE:
                if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    if (!PermissionUtil.mayCamera(getActivity(),
                            REQUEST_CAMERA,
                            new PermissionUtil.PermissionCallBack() {
                                @Override
                                public void shouldShowAlertDialog(String title) {
                                    mCallBack.shouldShowAlertDialog(title);
                                }
                            })) {
                        return;
                    }
                    openCamera();
                } else {
                    Toast.makeText(getActivity(), R.string.SDCard_not_authorization, Toast.LENGTH_SHORT).show();
                    dismiss();
                }
                break;
            case REQUEST_CAMERA:
                if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    Toast.makeText(getActivity(), R.string.camera_not_authorization, Toast.LENGTH_SHORT).show();
                    dismiss();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    mCallBack.onCamera(Utils.getImageFilePath());
                }else{
                    mCallBack.onCamera(null);
                }
                dismiss();
                break;
        }
    }

    public void requestPermissions(String title) {
        if ("需要打开相机才能拍照".equals(title)) {
            requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA);
        } else if ("需要打开SD卡读写权限才能拍照".equals(title)) {
            requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE);
        }
    }

    public interface CameraCallBack {
        void shouldShowAlertDialog(String title);

        void onCamera(String filePath);
    }

    public void setCameraCallBack(CameraCallBack mCallBack) {
        this.mCallBack = mCallBack;
    }
}
